import { _decorator, Component, Node, v3, CCInteger, Animation, find } from 'cc';
import { EnemyAttr, EnemyConstant } from './constant/EnemyConstant';
import { SysContant } from './constant/SysContant';
import { ScoreMgr } from './ScoreMgr';
import { AudioMgr } from './tool/AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Component {

    @property(CCInteger)
    enemyIndex: number

    enemyAttr: EnemyAttr
    scoreMgr: ScoreMgr;
    
    start() {
        this.enemyAttr = Object.assign({}, EnemyConstant.enemyAttrs[this.enemyIndex])

        this.scoreMgr = find('Canvas/control/score').getComponent(ScoreMgr)

    }

    update(deltaTime: number) {
        this.down(deltaTime)
    }

    down(dt: number) {

        let {x, y} = this.node.position

        this.node.setPosition(v3(x, y - dt * this.enemyAttr.speed * (SysContant.inst.bestRate() + 1)))

        if(y < -600) {
            this.die()
        }
    }



    killed(power: number = 1) {

        
        if(!this.enemyAttr) {
            console.log('-------', this.enemyAttr, '---', this.enemyIndex);
            console.log('position', this.node.position);
            
            return
        }
        

        if(this.enemyAttr.hp <= 0) {
            return
        }
        
        this.enemyAttr.hp -= power

        if(this.enemyAttr.hp <= 0) {
            
            // 播放死亡动画  音频
            this.node.getComponent(Animation).play(this.enemyAttr.dieName)
            
            AudioMgr.inst.audioSource.playing && AudioMgr.inst.playOneShot(this.enemyAttr.dieSound, 2)
    
            // 计分
            SysContant.inst.addScore(this.enemyAttr.score)
            // 显示分
            this.scoreMgr.showScore()
    
            // 消亡
            this.schedule(() => {this.node.destroy()}, 0.3)

        }

    }

    /**
     * 自然消亡
     */
    die() {
        this.node.destroy()
    }


}


